package com.liurong.controller;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.liurong.util.CustomException;

@Controller
public class LoginController {
	private final static Logger logger = Logger.getLogger(LoginController.class);

	@RequestMapping(value = "/login")
	public String login(Model model, HttpServletRequest request)
			throws Exception {
		logger.info("进入login方法!");
		// shiro在认证的时候抛出异常
		String exceptionClassName = (String) request
				.getAttribute("shiroLoginFailure");
		logger.info("shiro抛出的异常为：" + exceptionClassName);
		if (exceptionClassName != null) {
			if (UnknownAccountException.class.getName().equals(
					exceptionClassName)) {
				throw new CustomException("账号不存在");
			} else if (IncorrectCredentialsException.class.getName().equals(
					exceptionClassName)) {
				throw new CustomException("用户名/密码错误");
			} else if ("randomCodeError".equals(exceptionClassName)) {
				throw new CustomException("验证码错误");
			} else {
				throw new Exception();// 最终在异常处理器生成未知错误
			}
		}
		if (SecurityUtils.getSubject().isAuthenticated()) {
			logger.info("已经登录直接重定向到主页！");
			return "redirect:/to_index.do";
		}
		return "login";
	}

	@RequestMapping(value = "/to_index")
	public String toIndex(Model model, HttpServletRequest request)
			throws Exception {
		logger.info("进入toIndex方法！");
		return "index";
	}

	@RequestMapping(value = "/top")
	public String top() {
		logger.info("加载顶部！");
		return "top";
	}

	@RequestMapping(value = "left")
	public String left() {
		logger.info("加载左部！");
		return "left";
	}

	@RequestMapping(value = "main")
	public String main() {
		logger.info("加载main");
		return "main";
	}
}
